<template>
	<view class="paymentPage">
		<view class="payableAmount">
			<view class="title">实付金额</view>
			<view class="amount"><u-icon name="rmb" size="24"></u-icon>{{totalAmount}}</view>
		</view>
		<view class="sortTitle">请选择支付方式</view>
		<view class="paymentType">
			<view class="item" @click='checkPaymentType("balance")'>
				<u-icon label="会员扣款" name="https://supply.zhongyimotor.com/upload/applet/Member_deduction@3x.png"
					size="40" :margin-left="30" :label-size="30" label-color="#202020"></u-icon>
				<u-icon class="check"
					:name='paymentType == "balance"?"https://supply.zhongyimotor.com/upload/applet/icon_select_fill@2x.png":"https://supply.zhongyimotor.com/upload/applet/icon_select@2x.png"'
					size="40"></u-icon>
				<view class="balanceTips">可用余额 <u-icon name="rmb" label-color="#999999" size="24" :margin-left="4"
						:label-size="24" :label="balanceNum"></u-icon>
				</view>

			</view>
			<view class="item" @click='checkPaymentType("weChat")'>
				<u-icon label="微信支付" name="https://supply.zhongyimotor.com/upload/applet/WeChat_payment@3x.png"
					size="40" :margin-left="30" :label-size="30" label-color="#202020"></u-icon>
				<u-icon class="check"
					:name='paymentType == "weChat"?"https://supply.zhongyimotor.com/upload/applet/icon_select_fill@2x.png":"https://supply.zhongyimotor.com/upload/applet/icon_select@2x.png"'
					size="40"></u-icon>
			</view>
		</view>
		<view class="action">
			<u-button type="primary" :disabled="canPay" @click="toPay">确认支付</u-button>
			<u-button type="default" @click="toCancel">取消</u-button>
		</view>
		<u-popup v-model="balancePayShow" mode="bottom" border-radius="16">
			<view class="popupBox">
				<view class="popupTitle">
					请输入支付密码
					<view class="confirmBtn" @click="confirmPay">确认支付</view>
				</view>
				<view class="inputBox">
					<u-message-input mode="box" :disabled-keyboard="true" :breathe="false" :width="90" :maxlength="6"
						:dot-fill="true" :value="password"></u-message-input>
				</view>
				<u-keyboard class="uKeyboard" ref="uKeyboard" mode="number" @change="valChange" @backspace="backspace"
					v-model="keyboardShow" :confirm-btn="false" :cancel-btn="false" :mask="false"
					:safe-area-inset-bottom="true" :show-tips="false" :tooltip="false" :dot-enabled="false"
					:mask-close-able="false"></u-keyboard>
			</view>
		</u-popup>
		<u-no-network></u-no-network>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				keyboardShow: true,
				balancePayShow: false,
				balanceNum: 0,
				paymentType: "",
				canPay: true,
				hasPayPassword: false,
				password: ""
			}
		},
		props: {
			idList: {
				type: Array,
				default: () => [],
			},
			totalAmount: {
				type: Number,
				default: 0
			}

		},
		watch: {
			idList(newLength, oldLength) {}
		},
		onShow() {
			this.getInfo()
		},
		onReady() {
			this.getCurrentAmount()
		},
		methods: {

			getCurrentAmount() {
				let that = this
				that.$api.getMemberInfo().then(res => {
					that.balanceNum = res.result.currentAmount
				})
			},
			async confirmPay() {
				let that = this
				if (that.password.length < 6 || that.canPay) {
					return;
				}
				that.canPay = true
				let param = {
					payPassword: that.password
				}
				let checkPayRes = await that.$api.checkPayPassword(param)
				that.canPay = false
				that.password = ""
				if (checkPayRes.success) {
					let params = {
						idList: that.idList
					}
					that.$api.payByBalance(params).then((res) => {
						uni.setStorage({
							key: "currentAmount",
							data: that.accSub(that.balanceNum,
								that.totalAmount)
						})
						that.balanceNum = that.unitConverter(that.accSub(uni.getStorageSync("currentAmount"),
							that.totalAmount))
						uni.showToast({
							title: '支付成功',
							icon: "success",
							duration: 2000,
							success: () => {
								setTimeout(() => {
									that.$emit("clearTotalAmount")
									that.$emit("closePayPopup", false)
									that.$emit("reload")
								}, 2000)
							}
						})
					})
				}
			},
			checkPaymentType(e) {
				this.paymentType = e
				this.canPay = false
			},
			toCancel() {
				this.$emit("closePayPopup", false)
			},
			valChange(val) {
				let that = this
				// 将每次按键的值拼接到value变量中，注意+=写法
				if (this.password.length < 6) {
					this.password += val
				}
			},
			// 退格键被点击
			backspace() {
				// 删除value的最后一个字符
				if (this.password.length) this.password = this.password.substr(0, this.password.length - 1);
			},
			async toPay() {
				let that = this
				await that.$api.getInfo().then((res) => {
					if (res.result.payPassword != null && res.result.payPassword != "") {
						that.hasPayPassword = true
					}
				})
				switch (that.paymentType) {
					case "balance":
						if (!that.hasPayPassword) {
							uni.showModal({
								content: "您还未设置支付密码",
								confirmText: "前往设置",
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: `/pages/payPassword/index?from=order`
										})
									}
								}
							})
						} else {
							that.balancePayShow = true
						}
						break;
					case "weChat":
						wx.login({
							success: function(r) {
								let params = {
									code: r.code,
									"idList": that.idList,
								}
								that.$api.payByWeChat(params).then((res) => {
									uni.requestPayment({
										provider: 'wxpay', //支付类型-固定值
										timeStamp: res.result.timeStamp, // 时间戳（单位：秒）
										nonceStr: res.result.nonceStr, // 随机字符串
										package: res.result.package, // 固定值
										signType: res.result.signType, //固定值
										paySign: res.result.paySign, //签名
										success: function(res) {
											// console.log('success:' + JSON.stringify(res));
											uni.showToast({
												title: '支付成功',
												icon: "success",
												duration: 2000,
												success: () => {
													setTimeout(() => {
														that.$emit(
															"clearTotalAmount"
														)
														that.$emit(
															"closePayPopup",
															false
														)
														that.$emit(
															"reload"
														)
													}, 2000)
												}
											})
										},
										fail: function(err) {
											// console.log('fail:' + JSON.stringify(err));
											console.log("支付失败");
											uni.showToast({
												icon: 'error',
												title: '支付失败'
											})
										}
									});
								})
							}
						})
						break;
				}
			}
		}
	};
</script>

<style scoped lang="scss">
	/deep/.u-drawer {
		display: none !important
	}
</style>